<?php
namespace app\mini_api\controller;

class UserTelCode extends Api
{
    public function sendCode()
    {
        $map = [];
        $map['tel'] = $this->input_data['tel'];
        $map['create_time'] = ['>',time() - 300]; //10分钟有效

        if ( !$telcode = db('UserTelCode')->where($map)->order('id DESC')->find() )
        {
            $code = sprintf("%06d",rand(0,999999));
            #存到数据库
            $data['tel'] = $this->input_data['tel'];
            $data['create_time'] = time();
            $data['code'] = $code;
            db('UserTelCode')->insert($data);
        }
        else
        {
            if( $telcode['create_time'] + 60 > time() ) $this->resErr('1分钟之内只能发送一次'); 
            $code = $telcode['code'];
        }

        // 发送
        $tParam = [
            'code' => $code
        ];
        $data = [
            'tel' => $this->input_data['tel'],
            'tCode' => 'SMS_463590087', // 在阿里云的短信模板id,
            'tParam' => json_encode($tParam)
        ];
        $result = action('common/AliCloud/sendSms',$data);

        if($result !== true) $this->resErr('发送失败');

        $this->resSuc('ok');
    }

}
